/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin		 	*/
/*	Project:	GlbLib-1.0.0			*/
/*	Author:		gong_libin			*/
/*	Date:		2016_06_01			*/
/*	File:		GlbStream.cpp			*/
/********************************************************/

#include "GlbStream.h"

namespace GlbNet
{

CGlbStream::CGlbStream()
{
	m_pFunction = NULL;
}

CGlbStream::~CGlbStream()
{
}

void CGlbStream::GlbStreamAccept()
{
	int iSocket = 0;

	while (true) {
		if ((iSocket = accept(CGlbNet::m_iSocket, NULL, NULL)) > 0) {
			(*m_pFunction)(iSocket);
		}
	}

	return;
}

void CGlbStream::GlbStreamSetFunction(void (*pFunction)(int))
{
	m_pFunction = pFunction;

	return;
}

int CGlbStream::GlbStreamInit(char* pszUrl)
{
	struct sockaddr_un stAddr;

	stAddr.sun_family = GLB_AF_UNIX;
	strcpy(stAddr.sun_path, pszUrl);

	return GlbStreamOpenBind(&stAddr);
}

int CGlbStream::GlbStreamInit(struct sockaddr_un* pstAddr)
{
	return GlbStreamOpenBind(pstAddr);
}

int CGlbStream::GlbStreamOpenBind(struct sockaddr_un* pstAddr)
{
	if (GLB_SUCCESS == CGlbNet::GlbNetOpen(GLB_AF_UNIX, GLB_SOCK_STREAM)) {
		if (GLB_SUCCESS == GlbNetBind(pstAddr)) {
			if (listen(CGlbNet::m_iSocket, GLB_BACKLOG) < 0) {
				GLB_ERROR("%s\n", strerror(errno));
				CGlbNet::GlbNetClose();
				return GLB_FAILURE;
			}
		}
		else {
			GLB_ERROR("%s\n", strerror(errno));
			CGlbNet::GlbNetClose();
			return GLB_FAILURE;
		}
	}
	else {
		GLB_ERROR("%s\n", strerror(errno));
		CGlbNet::GlbNetClose();
		return GLB_FAILURE;
	}

	return GLB_SUCCESS;
}

int CGlbStream::GlbStreamConnect(char* pszUrl)
{
	struct sockaddr_un stAddr;

	stAddr.sun_family = GLB_AF_UNIX;
	strcpy(stAddr.sun_path, pszUrl);

	return GlbStreamConnect(&stAddr);
}

int CGlbStream::GlbStreamConnect(struct sockaddr_un* pstAddr)
{
	int iReturn = GLB_SUCCESS;

	if (GLB_SUCCESS == CGlbNet::GlbNetOpen(GLB_AF_UNIX, GLB_SOCK_STREAM)) {
		CGlbNet::GlbNetSetTimeOut(GLB_TIMEOUT, 0);
		if (connect(CGlbNet::m_iSocket, (struct sockaddr*)pstAddr, sizeof(struct sockaddr_un)) < 0) {
			GLB_ERROR("%s\n", strerror(errno));
			iReturn = GLB_FAILURE;
			CGlbNet::GlbNetClose();
		}
	}
	else {
		iReturn = GLB_FAILURE;
	}

	return iReturn;

}

} /* GlbNet */
